import promiseUtils from '@/core/utils/promiseUtils'
import upmsMenuApi from '@/core/upms/serverapi/upmsMenuServerApi'
import UpmsMenuAndAuthorityResponse from '@/core/upms/types/model/response/UpmsMenuAndAuthorityResponse'
import useAccountTokenInfoStore from '@/core/account/store/useAccountTokenInfoStore'
import useMenuStore from '@/core/upms/store/useMenuStore'

class UpmsMenuManager {
	getAllAdminMenuByCurrentAccount = async (): Promise<UpmsMenuAndAuthorityResponse[]> => {
		const token = useAccountTokenInfoStore.getState().accessToken
		return promiseUtils.ofResponse(upmsMenuApi.getAllAdminMenuByCurrentAccount(token)).check()
	}

	getAllMenuFromStoreOrServerApi = async (): Promise<UpmsMenuAndAuthorityResponse[]> => {
		const menuState = useMenuStore.getState()
		if (menuState.menus.length > 0) {
			return menuState.menus
		}
		return this.getAllAdminMenuByCurrentAccount().then(menus => {
			useMenuStore.setState({ menus: menus }, true)
			return menus
		})
	}
}

export default new UpmsMenuManager()
